

//
//  CenterViewController.m
//  蓝牙
//
//  Created by MyMac on 15/9/10.
//  Copyright (c) 2015年 tongfang. All rights reserved.
//

#import "CenterViewController.h"
#import <CoreBluetooth/CoreBluetooth.h>
NSString *const serviceUUIDStr=@"C3A8D954-4268-4416-BBF3-42BCC1D57AC6";
NSString *const characteristicUUIDStr=@"2DEFE2CD-70EE-4D6D-8E29-03670495D846";
@interface CenterViewController ()<CBCentralManagerDelegate,CBPeripheralDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (weak, nonatomic) IBOutlet UILabel *messageLabel;
@property(nonatomic,strong)CBCentralManager*manager;
@property(nonatomic,strong)CBCharacteristic*characteristic;
//@property(nonatomic,strong)CBService*service;
@property(nonatomic,strong)NSMutableData*data;
@property(nonatomic,strong)CBPeripheral*peripheral;
@end

@implementation CenterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.manager=[[CBCentralManager alloc]initWithDelegate:self queue:nil];
    
    
    
}
- (IBAction)writeClick:(id)sender {
    NSString*message=@"我要对周边写入数据";
    NSData*data=[message dataUsingEncoding:NSUTF8StringEncoding];
    [self.peripheral writeValue:data forCharacteristic:self.characteristic type:CBCharacteristicWriteWithResponse];
}
#pragma -mark CBCentralManagerDelegate
//管理者状态更新代理，，检测设备是否支持当前蓝牙版本
- (void)centralManagerDidUpdateState:(CBCentralManager *)central;
{
    switch (central.state) {
        case CBCentralManagerStatePoweredOn:
            //告诉中央，，开始寻找周边的设备，如果第一个参数为nil，则表示开始寻找周边的所有服务，以下传的UUID和周边的服务UUID一样，表示就是寻找这个UUID相匹的服务
            NSLog(@"正在寻找周边的蓝牙服务");
            [self.manager scanForPeripheralsWithServices:@[[CBUUID UUIDWithString:serviceUUIDStr]] options:@{CBCentralManagerScanOptionAllowDuplicatesKey:@YES}];
            break;
            
        default:
            NSLog(@"当前设备不支持蓝牙的版本");
            break;
    }
    
}
//中央发现了周边的服务，此时可以进行连接了
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
{
    NSLog(@"发现了周边服务");
    //一个附带着广播数据和信号质量(RSSI-Received Signal Strength Indicator)的周边被发现。这是一个很酷的参数，知道了信号质量，你可以用它去判断远近。任何广播、扫描的响应数据保存在advertisementData 中，可以通过CBAdvertisementData 来访问它
    [self.manager stopScan];//停止搜索周边服务
    if(self.peripheral!=peripheral){
        self.peripheral=peripheral;
        
    }
    
    [self.manager connectPeripheral:peripheral options:nil];//中央连接周边服务
    NSLog(@"正在连接周边");
    
}
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
    
    NSLog(@"连接周边成功");
    self.peripheral.delegate=self;
    self.data.length=0;
    [self.peripheral discoverServices:@[[CBUUID UUIDWithString:serviceUUIDStr]]];//让这个周边去发现自己的服务
    NSLog(@"周边寻找自己的服务");
    
}
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
    NSLog(@"连接周边服务失败:%@",error);
    
    
}
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
    
    NSLog(@"没有连接周边");
    
}
#pragma -mark CBPeripheralDelegate
//连接到了周边服务
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
{
    
    if(error==nil){
        NSLog(@"周边连接到了自己的服务");
        //从周边中遍利出自己想要的服务，，，再从这个服务中找出自己想要的特征，，，因为在一个周边中，可以有多个服务，而一个服务又可以有多个特征，，，所以通过UUID的标示，找到自己想要的服务和特征,我们想要的数据就在特征里面
        for(CBService*service in peripheral.services){
            if([service.UUID isEqual:[CBUUID UUIDWithString:serviceUUIDStr]]){
                //从服务里面找到特征
                [self.peripheral discoverCharacteristics:@[[CBUUID UUIDWithString:characteristicUUIDStr]] forService:service];
                NSLog(@"周边正在寻找自己服务里的特征");
            }
            
        }
    }else{
        
        NSLog(@"连接周边失败:%@",[error localizedDescription]);
        
    }
    
}
//找到这个特征，，，但并不知道特征的值
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
{
    
    if(error==nil){
        NSLog(@"找到周边服务里的特征");
        if([service.UUID isEqual:[CBUUID UUIDWithString:serviceUUIDStr ]]){
            for(CBCharacteristic*character in service.characteristics){
                if([character.UUID isEqual:[CBUUID UUIDWithString:characteristicUUIDStr]]){
                    
                    
                    [peripheral setNotifyValue:YES forCharacteristic:character];//再监听这个特征，看这个特征的是否又改变了,这个方法将导致下面的代理的回调，但如果要时刻监测这个特征值，就得设置监听这个特征值，如果特征值改变将会调用下面的一个代理
                }
            }
        }
    }
}
//特征更新的代理
-(void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
    self.characteristic=characteristic;
    if(error){
        NSLog(@"特征跟新失败");
        
    }
    if(![characteristic.UUID isEqual:[CBUUID UUIDWithString:characteristicUUIDStr]]){
        NSLog(@"不是我要的特征值");
        return;
        
    }
#warning  这个characteristic读不到特征值
    if(characteristic.isNotifying){
        NSLog(@"特征是改变了");
        //[peripheral readValueForCharacteristic:characteristic];//peripheral:didUpdateValueForCharacteristic:error立刻生效
        
    }else{
        [self.manager cancelPeripheralConnection:peripheral];
        
    }
    
    
}
//当特征的值被更新，会直接调用这个代理,从这里或得特征值
-(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
    
    NSMutableString*str=[[NSMutableString alloc]init];
    
    NSData*data=characteristic.value;
    NSString*message=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    [str appendString:self.messageLabel.text];
    [str appendString:message];
    self.messageLabel.text=str;
    NSLog(@"新特征消息:%@",message);
    self.peripheral=peripheral;
    //NSString*str1=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    //    NSString*path=[str1 stringByAppendingPathComponent:@"wen.png"];
    //    NSLog(@"%@",path);
    //  [data writeToFile:path atomically:YES];
    //    UIImage*image=[UIImage imageWithData:data];
    //   UIImageWriteToSavedPhotosAlbum(image, self, nil, nil);
    //    self.imageView.image=image;
    
    
}
-(void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
    if (error==nil) {
        NSLog(@"写入数据到周边");
    }
}
-(void)dealloc
{
    NSLog(@"%@释放了",self.class);

}

@end
